package com.zl.s;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Random;

/**
 * @description
 *
 * @date 2021-08-13 16:19
 *
 * @author Lizhong
 */
@Controller
@RequestMapping("/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;

    //登录
    @PostMapping("/insert")
    @ResponseBody
    public String test() {
        // 测试新增100条数据  根据id策略分布到各库
        for (int i = 0; i < 100; i++) {
            User user = new User();
            user.setSex(new Random().nextInt(2));
            user.setUserName("测试" + i);
            user.setCreateTime(new Date());
            user.setNum(i);
            this.userService.save(user);
        }
        return "ok";
    }

    @PostMapping("/queryById")
    @ResponseBody
    public User queryById(@RequestParam("id") Long id) {
        // 根据id查询用户信息
        User user = this.userService.getById(id);
        logger.info("用户信息:{}", user);
        return user;
    }



    @PostMapping("/updateById")
    @ResponseBody
    public boolean updateById(@RequestParam("id") Long id) {
        // 根据id查询用户信息
        User user = this.userService.getById(id);
        user.setSex(1000);
        boolean b=this.userService.updateById(user);
        return b;
    }



    @PostMapping("/deleteById")
    @ResponseBody
    public String delete(@RequestParam("id") Long id) {
        // 根据id查询用户信息
        boolean result = this.userService.removeById(id);
        logger.info("删除结果:{}", result);
        return "ok";
    }

    @PostMapping("/list")
    @ResponseBody
    public ResponseEntity<Page<User>> list() throws JSONException {
        // 查询列表
        return ResponseEntity.ok(this.userService.list());
    }


    @PostMapping("/count")
    @ResponseBody
    public JSONObject count() throws JSONException {
        // 查询列表
        int count = this.userService.count();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", count);
        return jsonObject;
    }
}